from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from server_chan.models import ServerChan
from user.models import User


def find_SCKEY_by_id(request):
    login_cookie = request.COOKIES.get('login-cookie')
    user_cookie = str(login_cookie).split('/')
    username = user_cookie[0]
    user = User(username=username)
    res = User.objects.filter(username=username)
    for i in res:
        user.username = i.username
        user.password = i.password
        user.SCKEY_ID = i.SCKEY_ID
    res = ServerChan.objects.filter(id=user.SCKEY_ID)
    SCKEY = '0'
    for i in res:
        SCKEY = i.SCKEY
    return JsonResponse({'SCKEY': SCKEY})


def modify_SCKEY(request):
    login_cookie = request.COOKIES.get('login-cookie')
    user_cookie = str(login_cookie).split('/')
    username = user_cookie[0]
    res = User.objects.filter(username=username)
    arr = []
    sckey_id = '0'
    for i in res:
        sckey_id = i.SCKEY_ID
    sckey_ = request.POST['SCKEY']
    chan = ServerChan
    if sckey_id is None:
        sc = ServerChan(SCKEY=sckey_)
        sc.save()
        User.objects.filter(username=username).update(SCKEY_ID=sc.id)
    else:
        chan.objects.filter(id=sckey_id).update(SCKEY=sckey_)
    return render(request, 'wechat.html')
